import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import mall from "@src/store/mall";

import { getCardShopList, getCouponShopList } from "@src/api/coupon"
import { getDistance } from "@src/common/utils";
import pageHandleUtil from "@src/common/pageHandleUtil";
import {getPrototype} from "@mall/api/good";
Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: mall,
    fields: ['curLocation']
  }],
  options: {
    multipleSlots: true,
    addGlobalClass: true
  },
  data: {
    //定义券类型3.
    couponTypeOptions: {
      GENERAL: "通用券",
      CASH: "代金券",
      DISCOUNT: "折扣券"
    },
    weekOptions: ["", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
    //有效期类型
    timeType: null,
    availablePeriods: null,
    couponPrototype: null,
    // 门店列表
    shopList: null,
    dialogShow: false,
    contentHeight: 0,
    showComponents: false,
    couponInstructionArr: "",
    couponViewHeight: 332,
    type: 'coupon'
  },
  methods: {
    open(goodsItem) {
      this.fetchData(goodsItem);
      this.setData({dialogShow: true})
    },
    fetchData(goodsItem) {
      this.setData({availablePeriods: null, couponPrototype: null, type: "coupon"})
      getPrototype(goodsItem.itemId).then(res => {
          let prototype = res.data[0]
          this.setData({
            availablePeriods: prototype.detail.availableTime,
            couponPrototype: prototype.detail.prototype,
            type: prototype.type
          })
        this.initShopList(prototype.type, this.data.couponPrototype)
        this.initData()
      })
    },
    initData() {
      // 格式化有效期
      console.log('this.data.couponPrototype', this.data.couponPrototype)
      let availableTime = JSON.parse(JSON.stringify(this.data.availablePeriods));
      let timeType = availableTime.timeType;
      this.setData({ timeType: timeType });
      let couponInstructionArr = {};
      if (availableTime.availablePeriod || availableTime.dateList) {
        console.log('availableTime.timeType', availableTime.timeType)
        if (availableTime.timeType == 1) {//领券后N天可用
          couponInstructionArr = { returnString: "领券后" + availableTime.days + "后可用", timeString: [] }
        } else if (availableTime.timeType == 2) {//规则星期可用
          couponInstructionArr = pageHandleUtil.dillCouponWeek([], false, availableTime);
        }
        else if (availableTime.timeType == 3) {//规则日期可用
          console.log('availableTime.timeType === 3', availableTime.timeType === 3)
          couponInstructionArr = pageHandleUtil.dillCouponDay([], false, availableTime);
        }
        else if (availableTime.timeType == 4) {//不规则日期可用
          let timeString = pageHandleUtil.mToStrArray(availableTime);
          let returnString = availableTime.dateList.replace(/:/g, "~");
          couponInstructionArr = { returnString: returnString, timeString: timeString }
        }
        //  }
      } else {
        couponInstructionArr = { returnString: `全部时段可用`, timeString: `` };
      }
      this.setData({ couponInstructionArr: couponInstructionArr })
      setTimeout(res => {
        this.getCouponViewHeight();
      }, 300)
    },
    initShopList(type, couponPrototype) {
      //获取经纬度
      this.updateStoreBindings()
      let lat = "";
      let long = ""
      if (this.data.curLocation) {
        lat = this.data.curLocation.latitude;
        long = this.data.curLocation.longitude
      }
      console.log('lat', lat);
      console.log('long', long)
      let shopList = [];
      if (type == 'card') {
        getCardShopList(couponPrototype.id).then(res2 => {
          let tempList = res2.data;
          tempList.forEach(item => {
            if (item.shops && item.shops.length > 0) {
              item.shops.forEach(item => {
                shopList.push(item)
              })
            }
          })
          shopList.forEach(item => {
            let distance = getDistance(lat, long, item.latitude, item.longitude)
            if (distance < 1000) {
              distance = distance + "米"
            } else {
              distance = (Math.round(distance / 100) / 10).toFixed(1) + "km"
            }
            item.distance = distance;
          })
          this.setData({ shopList: shopList })
        })
      } else {
        getCouponShopList(couponPrototype.id).then(res2 => {
          let tempList = res2.data;
          tempList.forEach(item => {
            if (item.shops && item.shops.length > 0) {
              item.shops.forEach(item => {
                shopList.push(item)
              })
            }
          })
          shopList.forEach(item => {
            let distance = getDistance(lat, long, item.latitude, item.longitude)
            if (distance < 1000) {
              distance = distance + "米"
            } else {
              distance = (Math.round(distance / 100) / 10).toFixed(1) + "km"
            }
            item.distance = distance;
          })
          console.log('shopList', shopList);
          this.setData({ shopList: shopList })
        })
      }
      this.setData({ shopList: shopList })
      console.log('shopList', this.data.shopList)
    },

    getCouponViewHeight() {
      let query = wx.createSelectorQuery().in(this);
      query.select('#scroll-b').boundingClientRect()
      query.selectViewport().scrollOffset()
      query.exec((res) => {
        let couponViewHeight = res[0].height;
        this.setData({couponViewHeight})
      })
    },
    //监听高度
    handleContentHeight(val) {
      this.setData({contentHeight: val.detail})
    },
    handleCallPhone(e) {
      wx.makePhoneCall({phoneNumber: e.currentTarget.dataset.phone})
    },
    handleToLocation(e) {
      let item = e.currentTarget.dataset.item
      wx.openLocation({latitude: item.latitude, longitude: item.longitude, scale: 18})
    },
  },

})
